package com.wzcl.app.service.impl;

import com.wzcl.app.dao.model.*;
import com.wzcl.app.dao.repository.*;
import com.wzcl.app.model.common.RVO;
import com.wzcl.app.model.dto.CatalogReportDto;
import com.wzcl.app.model.dto.EssayCourseCatalogDto;
import com.wzcl.app.model.dto.QuestionAnalysisImageDto;
import com.wzcl.app.service.CatalogTaskService;
import com.wzcl.app.service.EssayCourseCatalogService;
import com.wzcl.app.utils.BeanUtil;
import com.wzcl.app.utils.DateUtil;
import com.wzcl.app.utils.CollectionUtil;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author beingven
 * @Description TODO
 * @createTime 2020年12月23日 08:59:00
 */
@Service
public class EssayCourseCatalogServiceImpl implements EssayCourseCatalogService {
    @Resource
    private EssayCourseCatalogRepository catalogRepository;
    @Resource
    private CatalogTaskRepository catalogTaskRepository;
    @Resource
    private CourseRepository courseRepository;
    @Resource
    private CatalogTaskService catalogTaskService;
    @Resource
    private TaskEvaluateScoreRepository taskEvaluateScoreRepository;
    @Resource
    private EssayCourseStudyRecordRepository essayCourseStudyRecordRepository;
    @Resource
    private UserTaskQuizAnswerRepository userTaskQuizAnswerRepository;
    @Resource
    private EssayCourseQuestionBankRepository essayCourseQuestionBankRepository;

    @Override
    @Transactional
    public RVO createCatalog(EssayCourseCatalogDto essayCourseCatalogDto) {
        //获取系统当前时间
        Date date = DateUtil.getDateBySystemTime(System.currentTimeMillis());
        //对象转换
        EssayCourseCatalog essayCourseCatalog = BeanUtil.convertBean(essayCourseCatalogDto, new EssayCourseCatalog().getClass());
        essayCourseCatalog.setCreateTime(date);
        essayCourseCatalog.setUpdateTime(date);
        List<CatalogTask> catalogTaskList = essayCourseCatalogDto.getCatalogTaskList();
        essayCourseCatalog.setCourse(courseRepository.findAllByCourseId(essayCourseCatalogDto.getCourseId()));
        //章节保存
        EssayCourseCatalog save = catalogRepository.save(essayCourseCatalog);
        //章节任务填充
        for (int index = 0; index < catalogTaskList.size(); index++) {
            CatalogTask catalogTask = catalogTaskList.get(index);
            catalogTask.setCreateTime(date);
            catalogTask.setUpdateTime(date);
            catalogTask.setEssayCourseCatalog(catalogRepository.findCatalogById(save.getId()));
        }
        catalogTaskService.create(catalogTaskList);
        //删除所有关联id为空的数据
        catalogTaskRepository.deleteByIf();
        return RVO.success("保存成功");
    }

    @Override
    public void deleteCatalog(Integer id) {
        catalogRepository.deleteById(id);
    }

    @Override
    public List<EssayCourseCatalog> retrieveAll(Integer courseId) {
        List<EssayCourseCatalog> catalogList = catalogRepository.findAllByCourseId(courseId);
        List<EssayCourseCatalog> listBySort = CollectionUtil.getListBySort(catalogList, "getWhichLesson", "asc");
        return listBySort;
    }

    @Override
    public RVO getCatalogStar(Integer catalogId) {
        String phone = SecurityContextHolder.getContext().getAuthentication().getName();
        Integer star = 0;
        //获取当前章节下获得的所有星星
        List<CatalogTask> catalogTasks = catalogRepository.findCatalogById(catalogId).getCatalogTaskList();
        for (int index = 0; index < catalogTasks.size(); index++) {
            Integer starByTaskId = taskEvaluateScoreRepository.findStarByTaskId(catalogTasks.get(index).getId(), phone);
            if (starByTaskId == null){
                continue;
            }
            star+=starByTaskId;
        }
        //当前任务下所有星星
        Integer total = catalogTasks.size() * 3;
        //计算星星获得率
        Double getProbability = Double.valueOf(star) / Double.valueOf(total);
        if (getProbability == 0){
            return RVO.success("获取评分成功",0);
        }else if (getProbability < 0.5){
            return RVO.success("获取评分成功", 1);
        }else if (getProbability < 1){
            return RVO.success("获取评分成功", 2);
        }else {
            return RVO.success("获取评分成功", 3);
        }
    }

    @Override
    @Transactional
    public CatalogReportDto generateCatalogReport(Integer catalogId) {
        String phone = SecurityContextHolder.getContext().getAuthentication().getName();
        CatalogReportDto catalogReportDto = new CatalogReportDto();
        // 查询章节标题
        EssayCourseCatalog catalog = catalogRepository.findCatalogById(catalogId);
        catalogReportDto.setCatalogTitle(catalog.getMainTitle()+"："+catalog.getTranscriptTitle());
        // 计算评分
        catalogReportDto.setStar((Integer) getCatalogStar(catalogId).getData());
        Long dayNumber = 0l;
        Integer questionNumber = 0;
        Integer voiceNumber = 0;
        ArrayList<String> list = new ArrayList<>();
        ArrayList<QuestionAnalysisImageDto> questionAnalysis = new ArrayList<>();
        List<Integer> taskIds = catalogTaskRepository.findAllTaskId(catalogId);
        for (int index = 0; index < taskIds.size(); index++) {
            // 获取当前任务的学习记录
            EssayCourseStudyRecord studyRecord = essayCourseStudyRecordRepository.findByTaskId(taskIds.get(index));
            if (studyRecord != null){
                if (studyRecord.getEndTime() != null) {
                    dayNumber += DateUtil.getDays(studyRecord.getStartTime(), studyRecord.getEndTime());
                }else {
                    dayNumber += DateUtil.getDays(studyRecord.getStartTime(), DateUtil.getDateBySystemTime(System.currentTimeMillis()));
                }
            }
            // 获取累计答题数
            List<Integer> answerQuestionByTaskId = userTaskQuizAnswerRepository.getAnswerQuestionByTaskId(taskIds.get(index), phone);
            questionNumber += answerQuestionByTaskId.size();
            // 计算答过的题中语音题数量
            for (int inner = 0; inner < answerQuestionByTaskId.size(); inner++) {
                EssayCourseQuestionBank questionBank = essayCourseQuestionBankRepository.findQuestionBankById(answerQuestionByTaskId.get(inner));
                if (questionBank.getAudio() != null) {
                    voiceNumber++;
                }
            }
            //在答题表中查询是否有该任务的学习记录，如果有就提取出学习记录
            TaskEvaluateScore taskEvaluateScore = taskEvaluateScoreRepository.findByTaskId(taskIds.get(index), phone);
            if (taskEvaluateScore != null){
                list.add(catalogTaskRepository.findByTaskId(taskIds.get(index)).getLearningTarget());
            }

            //获取用户本章节下答错的题目并提取出错题解析
            List<Integer> mistakeQuestions = userTaskQuizAnswerRepository.getMistakeQuestionByTaskId(taskIds.get(index), phone);
            System.out.println(mistakeQuestions);
            for (int inner = 0; inner < mistakeQuestions.size(); inner++) {
                EssayCourseQuestionBank questionBank = essayCourseQuestionBankRepository.findQuestionBankById(mistakeQuestions.get(index));
                QuestionAnalysisImageDto questionAnalysisImageDto = new QuestionAnalysisImageDto(questionBank.getQuestionAnalysisImage(), questionBank.getQuestionAnalysisAudio());
                questionAnalysis.add(questionAnalysisImageDto);
            }
        }
        // 获取章节学习天数
        catalogReportDto.setStudyDay(dayNumber.intValue());
        // 计算当前章节累计答题数
        catalogReportDto.setQuestionNumber(questionNumber);
        // 计算口语表达次数
        catalogReportDto.setVoiceNumber(voiceNumber);
        // 计算积累素材数
        String materialList = catalogRepository.findCatalogById(catalogId).getWritingMethodBase().getMaterialList();
        List<String> listFromString = CollectionUtil.getListFromString(materialList, "|");
        catalogReportDto.setMaterialNumber(listFromString.size());
        // 获取学习收获
        catalogReportDto.setLearnTarget(list);
        // 获取错题解析
        catalogReportDto.setQuestionAnalysis(questionAnalysis);
        return catalogReportDto;
    }

    @Override
    public List<EssayCourseQuestionBank> retrieveAnalysisByCatalogId(Integer catalogId) {
        //根据章节拿到所有任务
        List<CatalogTask> taskList = catalogTaskRepository.findAllCatalog(catalogId);
        List<EssayCourseQuestionBank> list = new ArrayList<>();
        //查询任务下的所有题目
        for (int index = 0; index < taskList.size(); index++) {
            //拿到每个任务下所有的题目id
            List<String> questionList = CollectionUtil.getListFromString(taskList.get(index).getQuestionList(), ",");
            for (int inner = 0; inner < questionList.size(); inner++) {
                //根据题目id查询题目
                EssayCourseQuestionBank essayCourseQuestionBank = essayCourseQuestionBankRepository.findQuestionBankById(Integer.valueOf(questionList.get(index)));
                list.add(essayCourseQuestionBank);
            }

        }
        return list;
    }
}